#!/usr/bin/env python
# Create: 2018/12/6
__author__ = '749B'

import configparser
import getpass
import logging
import os.path

from utils.base64p import b64encode_str

logger = logging.getLogger(__name__)


class Config(object):

    def __init__(self, file):
        self.file = file

        self.abs_file = None
        self.config = self._config()
        self.new_node = None  # 如果是新加的配置，赋值该变量。ssh连接验证后，进行save()

    def _config(self):
        self.abs_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.file)
        config = configparser.ConfigParser()
        config.read(self.abs_file)
        return config

    def get_conf(self, host):
        """获取配置
        host存在，返回字典
        host不存在，返回None
        """
        if self.config.has_section(host):
            return {k: v for k, v in self.config.items(host)}

    def get_conf_or_hosts(self, node):
        """获取配置
        host存在，返回字典
        host不存在，返回所有host的列表
        """
        if self.config.has_section(node):
            return {k: v for k, v in self.config.items(node)}
        else:
            return self.config.sections()

    def get_or_create_conf(self, node):
        conf = self.get_conf(node)
        if not conf:
            self.config[node] = self.dialog()
            self.config[node].setdefault('host', node)
            self.new_node = node
            conf = self.get_conf(node)
        return conf

    @staticmethod
    def dialog():
        print("输入 q ，放弃并退出")
        fields = ['host', 'port', 'username', 'password', 'filename']
        d = {}
        for i in fields:
            if i == 'password':
                x = getpass.getpass('%s: ' % i)
                x = b64encode_str(x)
            else:
                x = input('%s: ' % i)
            if x in ['q', 'Q']:
                exit()
            d[i] = x
        for k, v in d.copy().items():
            if not v:
                d.pop(k)
        return d

    def save(self):
        if self.new_node is None:
            return
        logger.info("新增配置到配置文件 %s ,Node: %s" % (self.file, self.new_node))
        with open(self.abs_file, 'w') as config_file:
            self.config.write(config_file)



